// 引入外部资源
import { request } from "../../request/index";
import regeneratorRuntime from "../../libs/runtime";

Page({
  data: { goods: [], isFocus: false, inputValue: "" },
  TimeId: -1,

  // 输入框
  handleInput(e) {
    // 获取输入框的值
    const { value } = e.detail;
    // 判断合法性
    if (!value.trim()) {
      // 非法
      this.setData({ goods: [], isFocus: false, inputValue: "" });
      return;
    }

    this.setData({ isFocus: true });

    // TIPS 页面防抖功能(类似 Vue.js 的输入事件的 .lazy 修饰符)
    clearTimeout(this.TimeId);
    this.TimeId = setTimeout(() => {
      this.querySearch(value);
    }, 1000);
  },

  // 发送请求获取搜索值
  async querySearch(query) {
    const res = await request({ url: "/goods/qsearch", data: { query } });
    this.setData({ goods: res.data.message });
  },

  // 取消按钮
  handleCancel() {
    this.setData({
      inputValue: "",
      isFocus: false,
      goods: [],
    });
  },
});
